package riteh.proba.server.resources;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;

import com.google.gson.Gson;
import com.mysql.jdbc.Statement;

/*
 * TODO: CONNECTION CLOSE!!!
 */

//TODO: Zabraniti dodavanje samog sebe za prijatelja. Kod searcha sprjeciti nalezenje samog sebe.

@Path("/todos")
public class TodosResource {
	@Context
	UriInfo uriInfo;
	@Context
	Request request;

	ResultSet resultFromDb;

	Connection con = null;
	PreparedStatement pst = null;
	ResultSet rs = null;

	private static String url = "jdbc:mysql://localhost:3306/mydb";
	private static String user = "root";
	private static String password = "";

	private int execQueryLastId(String q) {
		// Connection con; //TODO: PROVJERITI! OPASNO!!!
		PreparedStatement statement;
		int res = 0;

		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			con = DriverManager.getConnection(url, user, password);
			statement = con
					.prepareStatement(q, Statement.RETURN_GENERATED_KEYS);
			statement.executeUpdate();

			ResultSet r = statement.getGeneratedKeys();
			r.next();

			res = r.getInt(1);
			con.close(); //TODO: NE RADI
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

		return res;
	}
	
	private void execQueryWithoutLastId(String q) {
		PreparedStatement statement;

		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			con = DriverManager.getConnection(url, user, password);
			statement = con
					.prepareStatement(q, Statement.RETURN_GENERATED_KEYS);
			statement.executeUpdate();

			con.close(); //TODO: NE RADI
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	@GET
	@Path("test")
	@Produces(MediaType.TEXT_PLAIN)
	public String test(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req) {
		servletResponse.setContentType("text/plain");

		String test[][] = { { "Brama", "Braminjo" }, { "Forica", "Bla" } };
		String proba;
		Gson gson = new Gson();

		proba = gson.toJson(test);

		System.out.println(proba);
		return proba;
	}

	@GET
	@Path("getID")
	@Produces(MediaType.TEXT_PLAIN)
	public String getID(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req) {
		String message;
		String id = "";

		servletResponse.setContentType("text/plain");

		if (req.getParameterMap().containsKey("name")) {
			message = req.getParameter("name");
			id += message;
		}
		return id;
	}

	@GET
	@Path("register")
	@Produces(MediaType.TEXT_PLAIN)
	public String tryRegister(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req) {
		System.out.println("Tu sam, Register");
		String firstName, lastName, birthDate, email, password, query;

		firstName = lastName = birthDate = email = password = query = "";

		servletResponse.setContentType("text/plain");

		if (req.getParameterMap().containsKey("name")) {
			firstName = req.getParameter("name");
		}
		if (req.getParameterMap().containsKey("surname")) {
			lastName = req.getParameter("surname");
		}
		if (req.getParameterMap().containsKey("email")) {
			email = req.getParameter("email");
		}
		if (req.getParameterMap().containsKey("password")) {
			password = req.getParameter("password");
		}
		if (req.getParameterMap().containsKey("date")) {
			birthDate = req.getParameter("date");
		}
		// Lucin is responsible that all data come to server so I will not test
		// this

		query = "INSERT INTO Korisnik (ImeKorisnika, PrezimeKorisnika, DatumRodjenja,"
				+ "Email, Password) VALUES ('"
				+ firstName
				+ "', '"
				+ lastName
				+ "',"
				+ "'"
				+ birthDate
				+ "', '"
				+ email
				+ "', '"
				+ password
				+ "')";

		// TODO: sto ako korisnik postoji u bazi? koju gresku vracam

		int userId = execQueryLastId(query);
		String res = Integer.toString(userId);
		System.out.println(res);

		try {
			int r = 0;
			/*
			 * Database db = new Database(); query =
			 * "INSERT INTO Krugovi (NazivKruga, KorisnikID) VALUES ('Not in any circle', "
			 * + r + ")"; db.Query(query, false); db.ExecuteUpdate();
			 * 
			 * query =
			 * "INSERT INTO Krugovi (NazivKruga, KorisnikID) VALUES ('Friendship requests', "
			 * + r + ")"; db.Query(query, false); db.ExecuteUpdate();
			 */
			query = "INSERT INTO Krugovi (NazivKruga, KorisnikID) VALUES ('Not in any circle', "
					+ userId + ")";
			r = execQueryLastId(query);
			/*
			 * query =
			 * "INSERT INTO Korisnik_Krugovi (KorisnikID, KrugoviID) VALUES (" +
			 * userId + ", " + r + ")"; execQueryLastId(query); //TODO: Baca
			 * exception jer u toj tablici nema indeksiranja!!! Najbolje
			 * iskoristiti neku drugu metodu za executeUpdate
			 */
			query = "INSERT INTO Krugovi (NazivKruga, KorisnikID) VALUES ('Sent requests', "
					+ userId + ")";
			r = execQueryLastId(query);
			/*
			 * query =
			 * "INSERT INTO Korisnik_Krugovi (KorisnikID, KrugoviID) VALUES (" +
			 * userId + ", " + r + ")"; execQueryLastId(query); //TODO: Baca
			 * exception jer u toj tablici nema indeksiranja!!! Najbolje
			 * iskoristiti neku drugu metodu za executeUpdate
			 */
			query = "INSERT INTO Krugovi (NazivKruga, KorisnikID) VALUES ('Recieved requests', "
					+ userId + ")";
			r = execQueryLastId(query);
		} catch (Exception e) {
		}

		return res;
	}

	@GET
	@Path("createCircle")
	@Produces(MediaType.TEXT_PLAIN)
	public String createCircle(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req) {
		String userID, circleName, circleColor, query;
		int userIDInt = 0;

		userID = circleColor = circleName = query = "";

		servletResponse.setContentType("text/plain");

		if (req.getParameterMap().containsKey("userId")) {
			userID = req.getParameter("userId");
			userIDInt = Integer.parseInt(userID);
		}
		if (req.getParameterMap().containsKey("circleName")) {
			circleName = req.getParameter("circleName");
		}
		if (req.getParameterMap().containsKey("circleColor")) {
			circleColor = req.getParameter("circleColor");
		}

		query = "INSERT INTO Krugovi (NazivKruga, Boja, KorisnikID) VALUES ('"
				+ circleName + "', '" + circleColor + "', " + userIDInt + ")";

		int r = execQueryLastId(query);
		String res = Integer.toString(r);
		System.out.println(res);

		return res;
	}

	@GET
	@Path("createEvent")
	@Produces(MediaType.TEXT_PLAIN)
	public String createEvent(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req) {
		String userID, eventDescription, eventDuration, eventPriority, circles[] = {}, tmp;
		String query;
		int userIDInt = 0;

		userID = eventDescription = eventDuration = eventPriority = query = "";

		servletResponse.setContentType("text/plain");

		if (req.getParameterMap().containsKey("userId")) {
			userID = req.getParameter("userId");
			userIDInt = Integer.parseInt(userID);
		}
		if (req.getParameterMap().containsKey("eventDescription")) {
			eventDescription = req.getParameter("eventDescription");
		}
		if (req.getParameterMap().containsKey("eventDuration")) {
			eventDuration = req.getParameter("eventDuration");
			Time t = new Time();
			eventDuration = t.AddTime(eventDuration);
		}
		if (req.getParameterMap().containsKey("eventPriority")) {
			eventPriority = req.getParameter("eventPriority");
		}
		if (req.getParameterMap().containsKey("circles")) {
			tmp = req.getParameter("circles");
			System.out.println(tmp);
			Gson gson = new Gson();
			circles = gson.fromJson(tmp, String[].class);
		}
		/*
		 * 1. dodati event u Eventi 2. dodati primljenje krugove u Event_Krugovi
		 */
		query = "INSERT INTO Eventi (`NazivEventa`, `Istek`, `Prioritet`, `KorisnikID`) "
				+ "VALUES ('"
				+ eventDescription
				+ "', '"
				+ eventDuration
				+ "', " + "'" + eventPriority + "', " + userIDInt + ")";

		int r = execQueryLastId(query);

		try {
			con.close();
		} catch (SQLException e) {
		}

		try {
			Database db = new Database();
			for (int i = 0; i < circles.length; i++) {
				query = "INSERT INTO Event_Krugovi (`EventID`, `KrugoviID`) VALUES "
						+ "(" + r + ", " + Integer.parseInt(circles[i]) + ")";
				db.Query(query, false);
				db.ExecuteUpdate();
			}
			db.Close();
		} catch (SQLException e) {
		} catch (Exception e) {
		}

		return "0";
	}

	/*
	 * TODO:
	 * Nesmijem vratiti samog sebe niti ljude koje imam za prijatelje
	 */
	@GET
	@Path("getPeople")
	@Produces(MediaType.TEXT_PLAIN)
	public String getPeople(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req) {
		String nameQuery = "", query, keywords[];
		int userId;

		servletResponse.setContentType("text/plain");

		if (req.getParameterMap().containsKey("nameQuery")) {
			nameQuery = req.getParameter("nameQuery");
		}

		keywords = nameQuery.split(" "); // Trebalo bi biti u if-u iznad al sta
											// reci
		query = "";

		try {
			con = DriverManager.getConnection(url, user, password);

			if (keywords.length == 1)
				query = "SELECT * FROM Korisnik WHERE `ImeKorisnika` LIKE '%"
						+ keywords[0] + "%' OR `PrezimeKorisnika` LIKE '%"
						+ keywords[0] + "%'";
			else
				query = "SELECT * FROM Korisnik WHERE `ImeKorisnika` LIKE '%"
						+ keywords[0] + "%' OR `ImeKorisnika` LIKE '%"
						+ keywords[1] + "%' OR `PrezimeKorisnika` LIKE '%"
						+ keywords[0] + "%' OR `PrezimeKorisnika` LIKE '%"
						+ keywords[1] + "%'";

			pst = con.prepareStatement(query);
			rs = pst.executeQuery();

			rs.last();
			int rowCount = rs.getRow();
			rs.beforeFirst();

			String users[][] = new String[rowCount][4];

			if (rowCount <= 0) {
				con.close(); // dodano extra
				return "";
			} else {
				int i = 0, j = 0;
				while (rs.next()) {
					users[i][j] = String.valueOf(rs.getInt(1));
					j++;
					users[i][j] = rs.getString(2);
					j++;
					users[i][j] = rs.getString(3);
					j++;
					users[i][j] = rs.getString(5);
					j = 0;
					i++;
				}
			}
			con.close();

			Gson gson = new Gson();
			System.out.println(gson.toJson(users));
			return gson.toJson(users);
		} catch (SQLException e) {
		}

		return "-1";
	}

	/*
	 * TODO:
	 * Nesmijem slati krugove u kojima nema ljudi
	 */
	@GET
	@Path("getCircles")
	@Produces(MediaType.TEXT_PLAIN)
	public String getCircles(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req) {
		String userId = "";
		int userIdInt = 0;

		servletResponse.setContentType("text/plain");

		if (req.getParameterMap().containsKey("userId")) {
			userId = req.getParameter("userId");
			userIdInt = Integer.parseInt(userId);
		}

		try {
			con = DriverManager.getConnection(url, user, password);
			String query = "SELECT * FROM `Krugovi` WHERE `KorisnikID` = "
					+ userIdInt;
			pst = con.prepareStatement(query);
			rs = pst.executeQuery();

			rs.last();
			int rowCount = rs.getRow();
			rs.beforeFirst();

			String circles[][] = new String[rowCount][3];

			if (rowCount <= 0) {
				con.close(); // dodano extra
				return "";
			} else {
				int i = 0, j = 0;
				while (rs.next()) {
					circles[i][j] = String.valueOf(rs.getInt(1));
					j++;
					circles[i][j] = rs.getString(2);
					j++;
					circles[i][j] = rs.getString(3);
					j = 0;
					i++;
				}
			}
			con.close();

			Gson gson = new Gson();
			System.out.println(gson.toJson(circles));
			return gson.toJson(circles);
		} catch (SQLException e) {
			return "-1";
		}
	}

	@GET
	@Path("getFriends")
	@Produces(MediaType.TEXT_PLAIN)
	public String getFriends(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req) {
		String userId = "";
		int userIdInt = 0;

		servletResponse.setContentType("text/plain");

		if (req.getParameterMap().containsKey("userId")) {
			userId = req.getParameter("userId");
			userIdInt = Integer.parseInt(userId);
		}

		try {
			con = DriverManager.getConnection(url, user, password);
			//TODO: napisati sub queryje umjesto inner joinova
			String query = "SELECT Korisnik.KorisnikID, Krugovi.KrugoviID, Korisnik.ImeKorisnika, Korisnik.PrezimeKorisnika FROM Korisnik INNER JOIN Korisnik_Krugovi ON Korisnik.KorisnikID=Korisnik_Krugovi.KorisnikID INNER JOIN Krugovi ON Korisnik_Krugovi.KrugoviID = Krugovi.KrugoviID WHERE Korisnik.KorisnikID IN (SELECT DISTINCT KorisnikID FROM Korisnik WHERE KorisnikID IN (SELECT DISTINCT KorisnikID FROM Krugovi WHERE KrugoviID IN (SELECT KrugoviID FROM Korisnik_Krugovi WHERE KorisnikID = " + userIdInt + " AND KrugoviID IN (SELECT KrugoviID FROM Krugovi WHERE KorisnikID IN (SELECT DISTINCT KorisnikID FROM Korisnik_Krugovi WHERE KrugoviID IN (SELECT KrugoviID FROM Krugovi WHERE korisnikID=" + userIdInt + ")))))) ORDER BY Krugovi.KrugoviID ASC";
System.out.println(query);
			pst = con.prepareStatement(query);
			rs = pst.executeQuery();

			rs.last();
			int rowCount = rs.getRow();
			rs.beforeFirst();

			String friends[][] = new String[rowCount][4];

			if (rowCount <= 0) {
				con.close(); // dodano extra
				return "";
			} else {
				int i = 0, j = 0;
				while (rs.next()) {
					friends[i][j] = String.valueOf(rs.getInt(1));
					j++;
					friends[i][j] = String.valueOf(rs.getInt(2));
					j++;
					friends[i][j] = rs.getString(3);
					j++;
					friends[i][j] = rs.getString(4);
					j = 0;
					i++;
				}
			}
			con.close();

			Gson gson = new Gson();
System.out.println(gson.toJson(friends));
			return gson.toJson(friends);
		} catch (SQLException e) {}

		return "0";
	}
	
	@GET
	@Path("sendFriendshipRequest")
	@Produces(MediaType.TEXT_PLAIN)
	public String sendFriendshipRequest(
			@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req) {
System.out.println("sendFriendshipRequest");
		String userId = "", selectedUserId = "";
		int userIdInt = 0, selectedUserIdInt = 0;

		servletResponse.setContentType("text/plain");

		if (req.getParameterMap().containsKey("userId")) {
			userId = req.getParameter("userId");
			userIdInt = Integer.parseInt(userId);
		}
		if (req.getParameterMap().containsKey("selectedUserId")) {
			selectedUserId = req.getParameter("selectedUserId");
			selectedUserIdInt = Integer.parseInt(selectedUserId);
		}

		try {
System.out.println("send2");
			con = DriverManager.getConnection(url, user, password);
			String query = "SELECT KrugoviID FROM Korisnik, Krugovi WHERE Korisnik.KorisnikID = " +
					"Krugovi.KorisnikID AND NazivKruga LIKE \"Sent requests\" AND Korisnik.KorisnikID = " + userIdInt;
System.out.println(query);
			pst = con.prepareStatement(query);
System.out.println("send2a");
			rs = pst.executeQuery();
System.out.println("send3");
			int sentCircleId = 0;
			while (rs.next()) {
				sentCircleId = rs.getInt(1);
			}
System.out.println(sentCircleId);
			
			query = "SELECT KrugoviID FROM Korisnik, Krugovi WHERE Korisnik.KorisnikID = " +
					"Krugovi.KorisnikID AND NazivKruga LIKE \"Recieved requests\" AND Korisnik.KorisnikID = " + selectedUserIdInt;
			pst = con.prepareStatement(query);
			rs = pst.executeQuery();
			rs.next();
			int recievedCircleId = rs.getInt(1);
System.out.println(recievedCircleId);
System.out.println(query);
			
			query = "INSERT INTO Korisnik_Krugovi VALUES (" + userIdInt + ", " + recievedCircleId + ")";
			pst = con.prepareStatement(query);
			pst.executeUpdate();
System.out.println(query);
			
			query = "INSERT INTO Korisnik_Krugovi VALUES (" + selectedUserId + ", " + sentCircleId + ")";
			pst = con.prepareStatement(query);
			pst.executeUpdate();
System.out.println(query);
			
			con.close();
			return "0";
		} catch (Exception e) {}

		return "";
	}

	@GET
	@Path("login")
	@Produces(MediaType.TEXT_PLAIN)
	public String tryLogin(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req) {
		System.out.println("Tu sam, Login");
		String email, pass;

		email = pass = "";
		servletResponse.setContentType("text/plain");

		if (req.getParameterMap().containsKey("email")) {
			email = req.getParameter("email");
		}
		if (req.getParameterMap().containsKey("password")) {
			pass = req.getParameter("password");
		}

		if (email == "" || pass == "") {
			return "0";
		} else {
			// connect to db and get id for user
			String query;

			query = "SELECT KorisnikID FROM Korisnik WHERE Email='" + email
					+ "' AND Password='" + pass + "'";

			try {
				Database db = new Database();
				db.Query(query, false);
				db.Execute();
				String tmp = db.GetResultAsString(1);
				db.Close();

				return tmp;
			} catch (Exception e) {}
		}
		return "0";
	}

	/*
	 * Home Activity
	 */
	@GET
	@Path("respondToEvent")
	@Produces(MediaType.TEXT_PLAIN)
	public String respondToEvent(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req) {
		String userId = "", eventId = "";
		int userIdInt = 0, eventIdInt = 0;

		servletResponse.setContentType("text/plain");

		if (req.getParameterMap().containsKey("userId")) {
			userId = req.getParameter("userId");
			userIdInt = Integer.valueOf(userId);
		}
		if (req.getParameterMap().containsKey("eventId")) {
			eventId = req.getParameter("eventId");
			eventIdInt = Integer.valueOf(eventId);
		}

		try {
			Database db = new Database();
			String query = "INSERT INTO Event_Odgovori (EventID, KorisnikID) VALUES ("
					+ eventIdInt + ", " + userIdInt + ")";
			System.out.println(query);
			db.Query(query, false);
			db.ExecuteUpdate();
			
			query = "UPDATE Eventi SET BrojOdgovora=BrojOdgovora+1 WHERE EventId="
					+ eventIdInt + "";
			System.out.println(query);
			db.Query(query, false);
			db.ExecuteUpdate();
			db.Close();
			return "0";
		} catch (Exception e) {
			return "-1";
		}
	}

	@GET
	@Path("usersWhoResponded")
	@Produces(MediaType.TEXT_PLAIN)
	public String usersWhoResponded(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req) {
		String eventId = "";
		int eventIdInt = 0;
		
		servletResponse.setContentType("text/plain");

		if (req.getParameterMap().containsKey("eventId")) {
			eventId = req.getParameter("eventId");
			eventIdInt = Integer.valueOf(eventId);
		}
		
		try {
			con = DriverManager.getConnection(url, user, password);
			String query = "SELECT Korisnik.KorisnikID, Korisnik.ImeKorisnika, " +
					"Korisnik.PrezimeKorisnika FROM Event_Odgovori, Korisnik WHERE " +
					"Event_Odgovori.KorisnikID = Korisnik.KorisnikID AND EventID = " + eventIdInt;
			pst = con.prepareStatement(query);
			rs = pst.executeQuery();

			rs.last();
			int rowCount = rs.getRow();
			rs.beforeFirst();

			String users[][] = new String[rowCount][3];

			if (rowCount <= 0) {
				con.close(); // dodano extra
				return "";
			} else {
				int i = 0, j = 0;
				while (rs.next()) {
					users[i][j] = String.valueOf(rs.getInt(1));
					j++;
					users[i][j] = rs.getString(2);
					j++;
					users[i][j] = rs.getString(3);
					j = 0;
					i++;
				}
			}
			con.close();

			Gson gson = new Gson();
			return gson.toJson(users);
		} catch (SQLException e) {}

		return "";
	}
	
	@GET
	@Path("getHomeEvents")
	@Produces(MediaType.TEXT_PLAIN)
	public String getHomeEvents(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req)
	{
		/*
		 * Input: userId, listOfCircles[], priorities[]
		 * userId ce sluziti da izbacim one evente ciji je userId vlasnik
		 * listOfCircles ce posluziti da pronadem sve evente, a priority ce
		 * sluziti da filtriram evente po samim priorityima.
		 * Znaci morat cu raditi dinamicki query!
		 */
		
		String userId = "", listOfCircles[] = {}, priority[] = {}, tmp = "";
		int userIdInt = 0;

		servletResponse.setContentType("text/plain");

		if (req.getParameterMap().containsKey("userId")) {
			userId = req.getParameter("userId");
			userIdInt = Integer.valueOf(userId);
		}
		if (req.getParameterMap().containsKey("listOfCircles")) {
			tmp = req.getParameter("listOfCircles");
			Gson gson = new Gson();
			listOfCircles = gson.fromJson(tmp, String[].class);			
		}
		if (req.getParameterMap().containsKey("priorities")) {
			tmp = req.getParameter("priorities");
			Gson gson = new Gson();
			priority = gson.fromJson(tmp, String[].class);
		}
		
		int nbOfCircles = listOfCircles.length;
		int nbOfPriority = priority.length;
		
		String query = "SELECT Eventi.EventID, Korisnik.ImeKorisnika, Eventi.NazivEventa, Eventi.Istek, Eventi.Prioritet, Eventi.BrojOdgovora FROM Eventi INNER JOIN Event_Krugovi ON Eventi.EventID=Event_Krugovi.EventID INNER JOIN Krugovi ON Event_Krugovi.KrugoviID=Krugovi.KrugoviID INNER JOIN Korisnik ON Krugovi.KorisnikID=Korisnik.KorisnikID WHERE (";
		
		for (int i=0; i < nbOfCircles; i++) {
			query += " Krugovi.KrugoviID = " + listOfCircles[i];
			if (i == nbOfCircles-1) break;
			query += " OR ";
		}
		query += ") AND (";
		
		for (int i=0; i < nbOfPriority; i++) {
			query += " Eventi.Prioritet LIKE '" + priority[i] + "'";
			if (i == nbOfPriority-1) break;
			query += " OR ";
		}
		query += ") AND NOT Eventi.KorisnikID = " + userIdInt + " GROUP BY Eventi.EventID";
		
System.out.println(query);

		try {
			con = DriverManager.getConnection(url, user, password);
			pst = con.prepareStatement(query);
			rs = pst.executeQuery();

			rs.last();
			int rowCount = rs.getRow();
			rs.beforeFirst();

			String events[][] = new String[rowCount][6];
			int i = 0, j = 0;
			
			Time t = new Time();

			if (rowCount > 0) {
				while (rs.next()) {
					events[i][j] = String.valueOf(rs.getInt(1));
					j++;
					events[i][j] = rs.getString(2);
					j++;
					events[i][j] = rs.getString(3);
					j++;
					//events[i][j] = t.TimeLeft(rs.getString(4));
					events[i][j] = rs.getString(4);
					j++;
					events[i][j] = rs.getString(5);
					j++;
					events[i][j] = String.valueOf(rs.getInt(6));
					j = 0;
					i++;
				}
				con.close(); // dodano extra
			} else {
				return "";
			}

			Gson gson = new Gson();

			System.out.println(gson.toJson(events));

			return gson.toJson(events);
		} catch(Exception e) {}
		
		return "0";
	}
	
	/*
	 * Profile activity
	 */
	@GET
	@Path("getProfileEvents")
	@Produces(MediaType.TEXT_PLAIN)
	public String getProfileEvents(
			@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req) {
		String id = "", query;
		int userId;

		servletResponse.setContentType("text/plain");

		if (req.getParameterMap().containsKey("userId")) {
			id = req.getParameter("userId");
		}
		userId = Integer.parseInt(id);

		query = "SELECT * FROM Korisnik, Eventi WHERE Korisnik.`KorisnikID` "
				+ "= Eventi.`KorisnikID` AND Korisnik.`KorisnikID` = " + userId;

		try {
			con = DriverManager.getConnection(url, user, password);
			pst = con.prepareStatement(query);
			rs = pst.executeQuery();

			rs.last();
			int rowCount = rs.getRow();
			rs.beforeFirst();

			String events[][] = new String[rowCount][4];
			int i = 0, j = 0;

			if (rowCount > 0) {
				while (rs.next()) {
					events[i][j] = String.valueOf(rs.getInt(8));
					j++;
					events[i][j] = rs.getString(9);
					j++;
					events[i][j] = rs.getString(10);
					j++;
					events[i][j] = rs.getString(12);
					j = 0;
					i++;
				}
				con.close(); // dodano extra
			} else {
				return "";
			}

			Gson gson = new Gson();

			System.out.println(gson.toJson(events));

			return gson.toJson(events);
		} catch (SQLException e) {
		}

		return "";
	}
	
	@GET
	@Path("deleteEvent")
	@Produces(MediaType.TEXT_PLAIN)
	public String deleteEvent(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req)
	{
		String userId = "", eventId = "";
		int userIdInt = 0, eventIdInt = 0;

		servletResponse.setContentType("text/plain");
		
		if (req.getParameterMap().containsKey("userId")) {
			userId = req.getParameter("userId");
			userIdInt = Integer.valueOf(userId);
		}
		if (req.getParameterMap().containsKey("eventId")) {
			eventId = req.getParameter("eventId");
			eventIdInt = Integer.valueOf(eventId);
		}
		
		try {
			Database db = new Database();
			String query = "";
			
			query = "DELETE FROM Event_Odgovori WHERE EventID = " + eventIdInt + " AND KorisnikID = " + userIdInt;
			db.Query(query, false);
			db.ExecuteUpdate();
			
			query = "DELETE FROM Event_Krugovi WHERE EventID = " + eventIdInt;
			db.Query(query, false);
			db.ExecuteUpdate();
			
			query = "DELETE FROM Eventi WHERE EventID = " + eventIdInt;
			db.Query(query, false);
			db.ExecuteUpdate();
			
			db.Close();
			return "0";
		} catch(Exception e) {
			return "-1";
		}
	}
	
	/*
	 * Circles Activity
	 */
	//3. manageUsersInCircle
	@GET
	@Path("manageUsersInCircle")
	@Produces(MediaType.TEXT_PLAIN)
	public String manageUsersInCircle(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req)
	{
		/*
		Description: Updates user list for selected circle
		Input: userId, circleId, users[][] = { {userId, action(add or remove)} … };
		Return: 0
		 */
		String userId = "", circleId = "", users[][] = {}, tmp = "";
		int userIdInt = 0, circleIdInt = 0;
		String deleteQuery = "", addQuery = "";

		servletResponse.setContentType("text/plain");
		
		if (req.getParameterMap().containsKey("userId")) {
			userId = req.getParameter("userId");
			userIdInt = Integer.valueOf(userId);
		}
		if (req.getParameterMap().containsKey("circleId")) {
			circleId = req.getParameter("circleId");
			circleIdInt = Integer.valueOf(circleId);
		}
		if (req.getParameterMap().containsKey("users")) {
			tmp = req.getParameter("users");
			Gson gson = new Gson();
			users = gson.fromJson(tmp, String[][].class);
		}
		
		try {
			Database db = new Database();
			
			int userIdTmp = -1, addOrRemove = -1;
			
			for (int i = 0; i < users.length; i++) {
				userIdTmp = Integer.parseInt(users[i][0]);
				addOrRemove = Integer.parseInt(users[i][1]);
				
				if (userIdTmp==-1 || addOrRemove==-1) return "-1";
				
				if (addOrRemove == 0) {
					deleteQuery = "DELETE FROM Korisnik_Krugovi WHERE KrugoviID = " + circleIdInt + " AND KorisnikID = " + userIdTmp;
					db.Query(deleteQuery, false);
					db.ExecuteUpdate();
				} else {
					addQuery = "INSERT INTO Korisnik_Krugovi VALUES(" + userIdTmp + ", " + circleIdInt + ")";
					execQueryWithoutLastId(addQuery);
				}
				userIdTmp = addOrRemove = 0;
			}
			db.Close();
		} catch (Exception e) {}
		
		return "0";
	}
	
	/*
	 4. deleteCircle
	 */
	@GET
	@Path("deleteCircle")
	@Produces(MediaType.TEXT_PLAIN)
	public String deleteCircle(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req)
	{
		String userId = "", circleId = "";
		int userIdInt = 0, circleIdInt = 0;

		servletResponse.setContentType("text/plain");
		
		if (req.getParameterMap().containsKey("userId")) {
			userId = req.getParameter("userId");
			userIdInt = Integer.valueOf(userId);
		}
		if (req.getParameterMap().containsKey("circleId")) {
			circleId = req.getParameter("circleId");
			circleIdInt = Integer.valueOf(circleId);
		}
		
		try {
			Database db = new Database();
			String q = "";

			con = DriverManager.getConnection(url, user, password);
			// dobiti id not in any circle
			//pobriso mu sve prijatelje, 
			q = "SELECT KrugoviID FROM Krugovi WHERE KorisnikID = " + userIdInt + " AND NazivKruga LIKE 'Not in any circle'";
System.out.println("id not in any circle" + q);
			int notInAnyCircleId = 0;
			pst = con.prepareStatement(q);
			rs = pst.executeQuery();
			
			while (rs.next()) {
				notInAnyCircleId = rs.getInt(1);	// = 12
			}
			
			if (notInAnyCircleId < 0) return "-1";
			
			// dobivanje korisnikovih id-ova od circla koji cemo pobrisat
			q = "SELECT KorisnikID FROM Korisnik_Krugovi WHERE KrugoviID = " + circleIdInt;
			pst = con.prepareStatement(q);
			rs = pst.executeQuery();
			
			int tmpUserId = 0;
			while (rs.next()) {
				tmpUserId = rs.getInt(1);
				q = "INSERT INTO Korisnik_Krugovi VALUES (" + tmpUserId + ", " + notInAnyCircleId + ")";
System.out.println("korisnikovi idovi (insert): " + q);
				execQueryWithoutLastId(q);
			}
			
			q = "DELETE FROM Korisnik_Krugovi WHERE KrugoviID = " + circleIdInt;
			db.Query(q, false);
			db.ExecuteUpdate();
			
			q = "DELETE FROM Krugovi WHERE KrugoviID = " + circleIdInt;
			db.Query(q, false);
			db.ExecuteUpdate();
			
			db.Close();
			con.close();
		} catch (Exception e) {}
		
		return "0";
	}
	
	/*
	[9:53:20 PM CEST] Ivan Lucin: i onda postaviti tog usera u te krugove
	5. manageCirclesForUser
	Input: userId, selectedUserId, circles[] = { circleId, ... };
	1. deletam tog prijatelja iz svih krugova
	2. pomicem tog prijatelja u krugove koje mi je poslao
	 */
	@GET
	@Path("manageCirclesForUser")
	@Produces(MediaType.TEXT_PLAIN)
	public String manageCirclesForUser(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req)
	{
		String userId = "", selectedUserId = "", tmp, circles[] = {};
		int userIdInt = 0, selectedUserIdInt = 0;

		servletResponse.setContentType("text/plain");
		
		if (req.getParameterMap().containsKey("userId")) {
			userId = req.getParameter("userId");
			userIdInt = Integer.valueOf(userId);
		}
		if (req.getParameterMap().containsKey("selectedUserId")) {
			selectedUserId = req.getParameter("selectedUserId");
			selectedUserIdInt = Integer.valueOf(selectedUserId);
		}
		if (req.getParameterMap().containsKey("circles")) {
			tmp = req.getParameter("circles");
			System.out.println(tmp);
			Gson gson = new Gson();
			circles = gson.fromJson(tmp, String[].class);
		}
		
		try {
			Database db = new Database();
			String q = "";
			int tmpCircleId = 0;
			q = "DELETE FROM Korisnik_Krugovi WHERE KorisnikID = " + selectedUserIdInt;
			db.Query(q, false);
			db.ExecuteUpdate();
			db.Close();
			
			for (int i = 0; i < circles.length; i++) {
				tmpCircleId = Integer.parseInt(circles[i]);
				
				if (tmpCircleId == 0) return "-1";
				
				q = "INSERT INTO Korisnik_Krugovi VALUES (" + selectedUserIdInt + ", " + tmpCircleId + ")";
				
				execQueryWithoutLastId(q);
				
				tmpCircleId = 0;
			}
		} catch(Exception e) {}
		
		return "0";
	}
	
	/*
	 6. removeFriendship
	 Description: Remove all connections between user and selected user
	 Input: userId, selectedUserId
	 Retrun: 0
	 */
	@GET
	@Path("removeFriendship")
	@Produces(MediaType.TEXT_PLAIN)
	public String removeFriendship(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req)
	{
		String userId = "", selectedUserId = "";
		int userIdInt = 0, selectedUserIdInt = 0;

		servletResponse.setContentType("text/plain");
		
		if (req.getParameterMap().containsKey("userId")) {
			userId = req.getParameter("userId");
			userIdInt = Integer.valueOf(userId);
		}
		if (req.getParameterMap().containsKey("selectedUserId")) {
			selectedUserId = req.getParameter("selectedUserId");
			selectedUserIdInt = Integer.valueOf(selectedUserId);
		}
		
		try {
			Database db = new Database();
			
			String q = "DELETE FROM Korisnik_Krugovi WHERE KrugoviID IN (SELECT KrugoviID FROM Krugovi WHERE KorisnikID=" + userIdInt + ") AND KorisnikID=" + selectedUserIdInt + "";
			
			db.Query(q, false);
			db.ExecuteUpdate();
			
			db.Close();
		} catch (Exception e) {}
		return "0";
	}
	
	/*
	 7. acceptFriendship
	 Description: Adds selected user to selected circles, sets friendship flag as true, and adds notifications to selected user 
	 Input: userId, selectedUserId, circles[] = {circleId};
	 Return: 0
	 */
	@GET
	@Path("acceptFriendship")
	@Produces(MediaType.TEXT_PLAIN)
	public String acceptFriendship(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req)
	{
		String userId = "", selectedUserId = "", tmp = "", circles[] = {};
		int userIdInt = 0, selectedUserIdInt = 0;

		servletResponse.setContentType("text/plain");
		
		if (req.getParameterMap().containsKey("userId")) {
			userId = req.getParameter("userId");
			userIdInt = Integer.valueOf(userId);
		}
		if (req.getParameterMap().containsKey("selectedUserId")) {
			selectedUserId = req.getParameter("selectedUserId");
			selectedUserIdInt = Integer.valueOf(selectedUserId);
		}
		if (req.getParameterMap().containsKey("circles")) {
			tmp = req.getParameter("circles");
			System.out.println(tmp);
			Gson gson = new Gson();
			circles = gson.fromJson(tmp, String[].class);
		}
		
		try {
			Database db = new Database();
			String q = "SELECT ImeKorisnika, PrezimeKorisnika FROM Korisnik WHERE KorisnikID = " + selectedUserIdInt;
			con = DriverManager.getConnection(url, user, password);
			pst = con.prepareStatement(q);
			rs = pst.executeQuery();
			
			String name, surname, report;
			name = surname = "";
			
			while (rs.next()) {
				name = rs.getString(1);
				surname = rs.getString(2);
			}
			
			for (int i = 0; i < circles.length; i++) {
				q = "INSERT INTO Korisnik_Krugovi VALUES (" + selectedUserIdInt + ", " + Integer.parseInt(circles[i]) + ")";
				execQueryWithoutLastId(q);
			}

			report = "Prijatelj " + name + " " + surname + " je prihvatio Vas zahtjev za prijateljstvom.";
			q = "INSERT INTO Korisnik_Obavijesti (KorisnikID, ObavijestTekst, Datum) VALUES (" + selectedUserIdInt + ", '" + report + "', '" + Calendar.getInstance().getTime() + "')";
			execQueryWithoutLastId(q);
			/*
			 ivan accepta bramu
			[6:02:50 PM CEST] Ivan Lucin: makni bramu iz recived (od ivana)
			[6:03:03 PM CEST] Ivan Lucin: smjesti bramu u circles
			[6:03:13 PM CEST] Ivan Lucin: makni ivana iz braminog sent
			[6:03:21 PM CEST] Ivan Lucin: smjesti ivana u bramin not in any
			 i posalji brami obavjest o prihvacanju
			 */
			
			q = "DELETE FROM Korisnik_Krugovi WHERE KrugoviID IN (SELECT KrugoviID FROM Krugovi WHERE KorisnikID = " + userIdInt + " AND NazivKruga LIKE 'Recieved requests')";
			db.Query(q, false);
			db.ExecuteUpdate();
			
			q = "DELETE FROM Korisnik_Krugovi WHERE KrugoviID IN (SELECT KrugoviID FROM Krugovi WHERE KorisnikID = " + selectedUserIdInt + " AND NazivKruga LIKE 'Sent requests')";
			db.Query(q, false);
			db.ExecuteUpdate();
			
			q = "SELECT KrugoviID FROM Krugovi WHERE KorisnikID = " + selectedUserIdInt + " AND NazivKruga LIKE 'Not in any circle'";
			con = DriverManager.getConnection(url, user, password);
			pst = con.prepareStatement(q);
			rs = pst.executeQuery();
			
			int id = 0;
			
			while (rs.next()) {
				id = rs.getInt(1);
			}
			
			q = "INSERT INTO Korisnik_Krugovi VALUES (" + userIdInt + ", " + id + ")";
			db.Query(q, false);
			db.ExecuteUpdate();
			
			db.Close();
			con.close();
		} catch(Exception e) {}
		
		return "0";
	}
	
	/*
	 2. editCircle
	 Description: Edits selected circle 
	 Input: userId, circleId, circleName, circleColor
	 Return: 0
	 */
	@GET
	@Path("editCircle")
	@Produces(MediaType.TEXT_PLAIN)
	public String editCircle(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req)
	{
		String userId = "", circleId = "", circleName = "", circleColor = "";
		int userIdInt = 0, circleIdInt = 0;

		servletResponse.setContentType("text/plain");
		
		if (req.getParameterMap().containsKey("userId")) {
			userId = req.getParameter("userId");
			userIdInt = Integer.valueOf(userId);
		}
		if (req.getParameterMap().containsKey("circleId")) {
			circleId = req.getParameter("circleId");
			circleIdInt = Integer.valueOf(circleId);
		}
		if (req.getParameterMap().containsKey("circleName")) {
			circleName = req.getParameter("circleName");
		}
		if (req.getParameterMap().containsKey("circleColor")) {
			circleColor = req.getParameter("circleColor");
		}
		
		try {
			Database db = new Database();
			String q = "UPDATE Krugovi SET NazivKruga='" + circleName + "', Boja='" + circleColor + "' WHERE KrugoviID= " + circleIdInt;
			
			db.Query(q, false);
			db.ExecuteUpdate();
			db.Close();
		} catch (Exception e) { return "-1"; }
		
		return "0";
	}
	
	/*
	 1. getProfileInfo
	 Description: Gets all user information
	 Input: userId
	 Return: name, surname, date, email
	 */
	@GET
	@Path("getProfileInfo")
	@Produces(MediaType.TEXT_PLAIN)
	public String getProfileInfo(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req)
	{
		String userId = "";
		int userIdInt = 0;

		servletResponse.setContentType("text/plain");
		
		if (req.getParameterMap().containsKey("userId")) {
			userId = req.getParameter("userId");
			userIdInt = Integer.valueOf(userId);
		}
		
		try {
			String q = "SELECT ImeKorisnika, PrezimeKorisnika, DatumRodjenja, Email FROM Korisnik WHERE KorisnikID = " + userIdInt;
			con = DriverManager.getConnection(url, user, password);
			pst = con.prepareStatement(q);
			rs = pst.executeQuery();
			String jsonArray[] = new String[4];
			
			while (rs.next()) {
				jsonArray[0] = rs.getString(1);
				jsonArray[1] = rs.getString(2);
				jsonArray[2] = rs.getString(3);
				jsonArray[3] = rs.getString(4);
			}
			
			con.close();
			
			Gson gson = new Gson();

			System.out.println(gson.toJson(jsonArray));

			return gson.toJson(jsonArray);
		} catch (Exception e) { return "-1"; }
	}
	
	/*
	 2. editProfileInfo
	 Description: Edits all user information
	 Input: userId, name, surname, date, email, passwordOld, passwordNew
	 Return: 0
	 */
	@GET
	@Path("editProfileInfo")
	@Produces(MediaType.TEXT_PLAIN)
	public String editProfileInfo(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req)
	{
		String userId = "", name = "", surname = "", date = "", email = "", passwordOld = "", passwordNew = "";
		int userIdInt = 0;

		servletResponse.setContentType("text/plain");
		
		if (req.getParameterMap().containsKey("userId")) {
			userId = req.getParameter("userId");
			userIdInt = Integer.valueOf(userId);
		}
		if (req.getParameterMap().containsKey("name")) {
			name = req.getParameter("name");
		}
		if (req.getParameterMap().containsKey("surname")) {
			surname = req.getParameter("surname");
		}
		if (req.getParameterMap().containsKey("date")) {
			date = req.getParameter("date");
		}
		if (req.getParameterMap().containsKey("email")) {
			email = req.getParameter("email");
		}
		if (req.getParameterMap().containsKey("passwordOld")) {
			passwordOld = req.getParameter("passwordOld");
		}
		if (req.getParameterMap().containsKey("passwordNew")) {
			passwordNew = req.getParameter("passwordNew");
		}
		
		try {
			String q = "SELECT * FROM Korisnik WHERE Email LIKE '" + email + "' AND Password LIKE '" + passwordOld + "'";
			con = DriverManager.getConnection(url, user, password);
			pst = con.prepareStatement(q);
			rs = pst.executeQuery();
			
			// wrong username or/and password
			if (!rs.next()) return "-1";
			
			q = "UPDATE Korisnik SET ImeKorisnika = '" + name + "', PrezimeKorisnika = '" + surname + "', DatumRodjenja = '" + date + "', Email = '" + email + "', Korisnik.Password = '" + passwordNew + "' WHERE KorisnikID = " + userIdInt;
			con.prepareStatement(q);
			pst.executeUpdate();
			
			con.close();
		} catch (Exception e) { return "-1"; }
		
		return "0";
	}
	
	/*
	 1. getNotifications
	 Description: Gets all notifications for a user and flags them as read
	 Input: userId
	 Return: notifications[] = {description}
	 */
	@GET
	@Path("getNotifications")
	@Produces(MediaType.TEXT_PLAIN)
	public String getNotifications(@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest req)
	{
		
		return "0";
	}
}